package com.zhiguang.cms.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.zhiguang.cms.entity.Article;
import com.zhiguang.cms.entity.Channel;
import com.zhiguang.cms.entity.User;

import com.zhiguang.cms.service.ArticleService;
import com.zhiguang.cms.service.UserService;
import com.zhiguang.cms.utils.CmsContant;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Value("${upload.path}")
	String uploadPath;
	
	
	@Autowired
	UserService userService;
	
	@Autowired
	ArticleService articleService;
	
	/**
	 * 跳转到注册页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value ="register", method=RequestMethod.GET )
	public String register(HttpServletRequest request) {
		request.setAttribute("user", new User());
		return "register";
	}
	
	
	/**
	 * 跳转到注册页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value="register", method=RequestMethod.POST)
	public String register(HttpServletRequest request,
			@Valid @ModelAttribute("user") User user,BindingResult result) {
		
		if(result.hasErrors()) {
			return  "register";
		}
		if(user.getUsername().contains("3")) {
			result.rejectValue("username", "", "用户名称不能包含数字3");
		}
		if(result.hasErrors()) {
			return  "register";
		}
		
		int reigsterResult = userService.register(user);
		
		if(reigsterResult>0) {
			return "redirect:login";	
		}
		request.setAttribute("error", "注册失败");
		return  "register";
		
		
	}
	
	/**
	 * 跳转到登陆页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(HttpServletRequest request) {
		request.setAttribute("user", new User());
		return "login";
	}
	
	/**
	 * 接收登录页面的数据 进行登录操作
	 * @param request
	 * @return
	 */
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,User user) {
		
		User loginUser = userService.login(user);
		if(loginUser!=null) {
			// 千万不要用hard code 硬编码
			request.getSession().setAttribute(CmsContant.USER_KEY, loginUser);
			return loginUser.getRole() ==CmsContant.ROLE_ADMIN ? "redirect:/admin/index" :  "redirect:/user/home";
		}
		
		return "login";
	}
	
	@RequestMapping("logout")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute(CmsContant.USER_KEY);
		return "redirect:/index";
	}
	
	/**
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping("checkuser")
	@ResponseBody
	public boolean checkuser(String username) {
		User user  = userService.findByName(username);
		return (user==null);
	}
	
	/**
	 * 
	 * @param requeat
	 * @return
	 */
	@RequestMapping("home")
	public String home(HttpServletRequest requeat) {
		return "home/index";
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("addArticle")
	public String addArticle(HttpServletRequest request) {
		List<Channel> channels =  articleService.listChannels();
		request.setAttribute("channels", channels);
		return "home/addarticle";
	}
	
	/**
	 * 
	 * @param request
	 * @param article
	 * @param file
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@PostMapping("addArticle")
	@ResponseBody
	public String addArticle(HttpServletRequest request,Article article,MultipartFile file) throws IllegalStateException, IOException {
		
		User loginUser = (User)request.getSession().getAttribute(CmsContant.USER_KEY);
		if(loginUser==null) {
			return "failed";
		}
		
		String picture = processFile(file);
		article.setPicture(picture);
		article.setUserId(loginUser.getId());
		articleService.add(article);
		
		return "success";
	}
	
	/**
	 * 
	 * @param file
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	private String processFile(MultipartFile file ) throws IllegalStateException, IOException {
		
		
		if(file==null||file.isEmpty())
			return "";
		String fileName = file.getOriginalFilename();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String todayStr = format.format(new Date());
		
		//计算上传的路径
		String path=uploadPath +"/" +  todayStr;
		File pathFile = new File(path);
		//如果上传的路径不存在 则创建该目录
		if(!pathFile.exists()) {
			pathFile.mkdirs();
		}
		
		System.out.println("filename is " + fileName);
		
		//计算原来文件的扩张名
		String suffixName = fileName.substring(fileName.lastIndexOf('.'));
		
		// 随机生成一个文件名
		String newFileName = UUID.randomUUID().toString() + suffixName;
		
		// 计算新的文件的绝对路径
		file.transferTo(new File( path + "/" + newFileName));
		
		return todayStr + "/" + newFileName;
		
	}
	
	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping("myarticles")
	public String myarticles(HttpServletRequest request,
			@RequestParam(defaultValue="1") int page) {
		
		User loginUser = (User)request.getSession().getAttribute(CmsContant.USER_KEY);
		if(loginUser==null) {
			return "tologin";
		}
		PageInfo<Article> articlePage = articleService.listByUser(loginUser.getId(),page);
		request.setAttribute("articlePage", articlePage);
		return "home/myarticles";
		
		
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("delArticle")
	@ResponseBody
	public String delArticle(int id) {
		
		//这里需要判断文章是不是自己的，如果不是自己的不允许删除
		articleService.detete(id);
		return "success";
		
	}
	
	/**
	 * 显示文章详情
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("article")
	public String article(HttpServletRequest request,int id) {
		
		Article article = articleService.getById(id);
		request.setAttribute("article", article);
		return "home/articleDetail";
		
		
	}
	
	
		
	
}
